package com.ai.notices.web.system;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.support.RequestContext;

import com.ai.notices.common.util.HttpConstants;
import com.ai.notices.common.util.JsonDateValueProcessor;
import com.ai.notices.common.vo.comm.QueryParamsVo;
import com.fasterxml.jackson.databind.ObjectMapper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

/**
 * BaseController
 * @author lixc
 */
public class AppBaseController {
	private static final Logger logger = Logger.getLogger(AppBaseController.class);

	@Autowired
	protected HttpServletRequest request;
	@Autowired
	protected HttpSession session;
	@Autowired
	protected ServletContext servletContext;
	
	protected RequestContext requestContext;
	
	public static final String CONTENTTYPE_HTML = "text/html";
	public static final String CONTENTTYPE_JSON = "application/json";
    public static final String CHARTSET_UTF8 = "utf-8";
    
    
    
    /**
     * 从Request获取参数
     * @param name
     * @return
     */
    final protected String getParam(String name){
    	return request.getParameter(name);
    }
    
    /**
     * 从Request获取参数，去除头尾空格
     * @param name
     * @return
     */
    final protected String getParamTrim(String name){
    	return StringUtils.trimToEmpty(request.getParameter(name));
    }
    
    /**
     * 从Request获取参数
     * @param name
     * @return
     */
    final protected String[] getParams(String name){
    	return request.getParameterValues(name);
    }
    
    /**
     * 获取参数为Map
     * @return
     */
	final protected Map<String,String> getParamMap(){
    	Map<String, String> m = new HashMap<String, String>();
        Iterator<String> keys = request.getParameterMap().keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            m.put(key, getParam(key));
        }
        return m;
    }
	
	final protected String getMessages(String code){
		if(requestContext == null){
			requestContext = new RequestContext(request);
		}
		
		return requestContext.getMessage(code);
	}
	
	
	protected void setPageInfo(QueryParamsVo params){
		String pageSize = this.getParam("pageSize");
		String pageNo = this.getParam("pageNo");
		if(StringUtils.isBlank(pageSize) == false){
			try{
			    params.setPageSize(Integer.parseInt(pageSize));
			}catch(Exception e){}
		}
		
		if(StringUtils.isBlank(pageNo) == false){
			try{
			    params.setPageNo(Integer.parseInt(pageNo));
			}catch(Exception e){}
		}
	}
	
    protected String toJsonString(Object obj){
    	try {
			return new ObjectMapper().writeValueAsString(obj);
		} catch (Exception e) {
		}
    	return "{}";
    }
    
	//获取浏览器端客户IP地址
    protected String getClientAddr(){
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        	ip = request.getHeader("x-real-ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        
        if(ip != null && ip.contains(",")){
        	//CDN返回多组ip
        	ip = ip.split(",")[0];
        }
        return ip;
    }

	/**
	 * 返回服务端处理结果
	 * @param obj 服务端输出对象
	 * @return 输出处理结果给前段JSON格式数据
	 * @author YANGHONGXIA
	 * @since 2015-01-06
	 */
	public String responseResult(Object obj){
		JSONObject jsonObj = null;
		if(obj != null){
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
			jsonObj = JSONObject.fromObject(obj, jsonConfig);
			logger.info("后端返回数据：" + jsonObj);
			if(HttpConstants.SERVICE_RESPONSE_SUCCESS_CODE.equals(jsonObj.getString(HttpConstants.SERVICE_RESPONSE_RESULT_FLAG))){
				jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, false);
				jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, "");
			}else{
				jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, true);
				String errMsg = jsonObj.getString(HttpConstants.SERVICE_RESPONSE_RESULT_MSG);
				jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, errMsg==null?HttpConstants.SERVICE_RESPONSE_NULL:errMsg);
			}
		}
		return jsonObj.toString();
	}

	/**
	 * 返回成功
	 * @param obj 输出对象
	 * @return 输出成功的JSON格式数据
	 */
	public String responseSuccess(Object obj){
		JSONObject jsonObj = null;
		if(obj != null){
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
			jsonObj = JSONObject.fromObject(obj, jsonConfig);
			logger.info("后端返回数据：" + jsonObj);
			jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, false);
			jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, "");
		}
		return jsonObj.toString();
	}

	/**
	 * 返回成功
	 * @param obj 输出对象
	 * @return 输出成功的JSON格式数据
	 */
	public String responseArraySuccess(Object obj){
		JSONArray jsonObj = null;
		if(obj != null){
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
			jsonObj = JSONArray.fromObject(obj, jsonConfig);
			logger.info("后端返回数据：" + jsonObj);
		}
		return jsonObj.toString();
	}

	/**
	 * 返回成功
	 * @param obj 输出对象
	 * @return 输出成功的JSON格式数据
	 */
	public String responseSuccess(Object obj, String msg){
		JSONObject jsonObj = null;
		if(obj != null){
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
			jsonObj = JSONObject.fromObject(obj, jsonConfig);
			logger.info("后端返回数据：" + jsonObj);
			jsonObj.element(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, false);
			jsonObj.element(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, msg);
		}
		return jsonObj.toString();
	}

	/**
	 * 返回失败
	 * @param errorMsg 错误信息
	 * @return 输出失败的JSON格式数据
	 */
	public String responseFail(String errorMsg){
		JSONObject jsonObj = new JSONObject();
		jsonObj.put(HttpConstants.RESPONSE_RESULT_FLAG_ISERROR, true);
		jsonObj.put(HttpConstants.SERVICE_RESPONSE_RESULT_MSG, errorMsg);
		return jsonObj.toString();
	}
    
}
